/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.dialog.xpath.model;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.model.Server;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeReader;
import offset.nodes.client.virtual.model.GetSchemas;

/**
 *
 * @author Walter Luetgenau
 */
public class XPathModel {

    Server server;

    public XPathModel(Server server) {
        this.server = server;
    }

    public String getXPathQuery(String path) throws Exception {
        GetXPathSearch.Request request = new GetXPathSearch.Request();

        request.setPath(path);
        GetXPathSearch.Response response = (GetXPathSearch.Response) server.sendRequest(request);

        return response.getXpathQuery();
    }

    public String getTemporaryXPathQuery(String key) throws Exception {
        GetXPathSearch.Request request = new GetXPathSearch.Request();

        request.setKey(key);
        GetXPathSearch.Response response = (GetXPathSearch.Response) server.sendRequest(request);

        return response.getXpathQuery();
    }

    public void setXPathQuery(String path, String xpathQuery) throws Exception {
        SetXPathSearch.Request request = new SetXPathSearch.Request();

        request.setPath(path);
        request.setXpathQuery(xpathQuery);

        SetXPathSearch.Response response = (SetXPathSearch.Response) server.sendRequest(request);
    }

    public NodeTypes getNodeTypes() {
        GetSchemas.Request request = new GetSchemas.Request();
        GetSchemas.Response response = null;
        try {
            response = (GetSchemas.Response) server.sendRequest(request);
            InputStream in = new ByteArrayInputStream(response.getSchemaXml().getBytes());
            NodeTypeDefinition[] definitions = NodeTypeReader.read(in);
            
            NodeTypes types = new NodeTypes(definitions);
            
            return types;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
